
use std::fmt;
use std::mem;

///颠倒元组元素
fn reverse(pair: (i32, bool))-> (bool, i32){
    // 使用let绑定元组中的各项到变量
    let (integer, boolean) = pair;
    (boolean, integer)
}

fn transpose(matrix: Matrix) -> Matrix
{
    let new_matrix = Matrix(matrix.0, matrix.2, matrix.1, matrix.3);
    new_matrix
}

#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);

impl Matrix {
    fn add(&self) -> f32 {
         return self.0 + self.1 + self.2 + self.3;
    }
}

impl fmt::Display for Matrix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\n({}, {})\n({}, {})", self.0, self.1, self.2, self.3)
    }
}

/// 字面量和运算符
fn main() {

    // u32 -- 无符号32位整型后缀
    // i32 -- 有符号32位整型后缀
    // 0x -- 十六进制前缀
    // 0o -- 八进制前缀
    // 0b -- 二进制前缀
    // _  -- 数字可读性
    // true  ,  false  ,  &&, ||, !
    // &,|,^  << , >>   位运算
    println!("1 + 2 = {}", 1u32 + 2);
    println!("1 - 2 = {}", 1i32 - 2);
    println!("1000 = {}", 1_000);
    println!("{}", true && false);
    println!("{}", 0b_01 & 0b_101);
    println!("{}", 2 << 2);

    //元组: 是不同类型的值的集合,函数可返回元组. (i32, u32, f32, bool)  用()构造
    let pair = (1, true);
    println!("pair.0 is {:?}", pair.0);
    println!("pair is {:?}", reverse(pair));
    // 解构
    match pair{
        (a, _) => println!("元组第一个元素为：{}", a),
    }

    // 太长的元组, 不能打印
    // let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
    // println!("too long tuple: {:?}", too_long_tuple);

    let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
    println!("matrix: {:?}", matrix);
    println!("matrix: {}", matrix);
    println!("matrix.add: {0:.3}", matrix.add());
    println!("transpose: {}", transpose(matrix));


    let matrix2 = Matrix(1.1, 2.2, 3.3, 4.4);
    // 解构
    match matrix2 {
        Matrix(a, _, _, _) => println!("matrix2: a={} - {:?}", a, matrix2),
    }


    // 数组 -- 切片

    let xs: [usize; 5] = [1, 2, 3, 4, 5];
    println!("xs: {:?}", xs);
    println!("xs-0: {:?}", xs[0]);
    let xs2 = vec![1,2,3,4,5];
    println!("xs2: {:?}", xs2);
    let ys: [i32; 50] = [0; 50];
    println!("ys: {:?}", ys);
    println!("ys-10: {}", ys[10]);
    println!("ys-长度为: {}", ys.len());

    println!("ys-栈内存分配为: {} 字节", mem::size_of_val(&ys));

    println!("xs[1..4]-为: {:?}", &xs[1..4]);
    println!("xs[1..4]-长度为: {}", &xs[1..4].len());
}
